package com.getpebble.android.framework.endpoint;

import com.getpebble.android.bluetooth.protocol.ProtocolMessage;
import com.getpebble.android.common.version.AndroidPebbleAppVersion;
import com.getpebble.android.framework.protocol.EndpointId;
import com.getpebble.android.framework.protocol.inbound.PblInboundPhoneVersionMessage;
import com.getpebble.android.framework.protocol.outbound.PblOutboundPhoneVersionMessage;
import java.util.Collections;
import java.util.EnumSet;
import java.util.Set;

class PhoneVersionEndpoint extends Endpoint {
    private static final String TAG = PhoneVersionEndpoint.class.getSimpleName();
    private static final Set<EndpointId> sIds = Collections.unmodifiableSet(EnumSet.of(EndpointId.PHONE_VERSION));
    private final Listener mListener;
    private final IEndpointMessageSender mMessageSender;

    interface Listener {
        boolean onReceive(PblInboundPhoneVersionMessage pblInboundPhoneVersionMessage);
    }

    PhoneVersionEndpoint(IEndpointMessageSender messageSender, Listener listener) {
        if (messageSender == null) {
            throw new IllegalArgumentException("'messageSender' cannot be null!");
        }
        this.mMessageSender = messageSender;
        this.mListener = listener;
    }

    Set<EndpointId> getSupportedEndpoints() {
        return sIds;
    }

    private Listener getListener() {
        return this.mListener;
    }

    private IEndpointMessageSender getMessageSender() {
        return this.mMessageSender;
    }

    boolean sendResponse() {
        return getMessageSender().sendMessage(new PblOutboundPhoneVersionMessage(AndroidPebbleAppVersion.getVersionInfo()));
    }

    boolean onReceive(ProtocolMessage message) {
        if (message.getEndpointId() != EndpointId.PHONE_VERSION.getCode()) {
            return false;
        }
        PblInboundPhoneVersionMessage phoneVersionMessage = new PblInboundPhoneVersionMessage(message);
        Listener listener = getListener();
        if (listener != null && listener.onReceive(phoneVersionMessage)) {
            return true;
        }
        sendResponse();
        return true;
    }
}
